package cn.stylefeng.guns.modular.storage.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.storage.entity.StorageOut;
import cn.stylefeng.guns.modular.storage.entity.StorageOutDetailed;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutDetailedParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutDetailedResult;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageOutService;
import cn.stylefeng.guns.sys.core.util.CacheUtil;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 拣货单表控制器
 */
@Controller
@RequestMapping("/storageOut")
public class StorageOutController extends BaseController {


    private String PREFIX = "/storage/storageOut";

    @Autowired
    private StorageOutService storageOutService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrderTransportService orderTransportService;
    @Autowired
    private StorageOutDetailedService storageOutDetailedService;
    @Autowired
    private BasicWarehouseService basicWarehouseService;
    @Autowired
    private BasicCustomerService basicCustomerService;

    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/storageOut.html";
    }

    /**
     * 拣货单打印页面
     */
    @RequestMapping("tostorageOutPrint")
    public String tostorageOutPrint(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/storageOutPrint.html";
    }

    /**
     * 拣货单查询页面
     */
    @RequestMapping("toStorageOutQuery")
    public String toStorageOutQuery(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/storageOutQuery.html";
    }

    /**
     * 拣货单查询页面
     * 云仓
     */
    @RequestMapping("toStorageOutQueryTool")
    public String toStorageOutQueryTool(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/storageOutQueryTool.html";
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/storageOut_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/storageOut_edit.html";
    }

    /**
     * 批量分配备货区页面
     */
    @RequestMapping("/toPointsStockup")
    public String toPointsStockup() {
        return PREFIX + "/pointsStockup.html";
    }

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(StorageOutParam storageOutParam) {
        this.storageOutService.add(storageOutParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(StorageOutParam storageOutParam) {
        this.storageOutService.update(storageOutParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(StorageOutParam storageOutParam) {
        this.storageOutService.delete(storageOutParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(StorageOutParam storageOutParam) {
        StorageOut detail = this.storageOutService.getById(storageOutParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 合单
     * @param ids
     * @return
     */
    @RequestMapping("/startContract")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public  ResponseData startContract(@RequestParam("ids") Long[] ids){
    	String uuid = UUID.randomUUID().toString().replaceAll("-","");
        for (Long id :ids) {
            try {
                StorageOut storageOut = storageOutService.getById(id);
                storageOut.setMark(uuid);
                storageOut.setRepetition(uuid);
                StorageOutParam stor = new StorageOutParam();
                ToolUtil.copyProperties(storageOut,stor);
                storageOutService.update(stor);
            } catch (Exception e) {
                break;
            }
        }
        return ResponseData.success();
    }

    /**
     * 取消合单
     * @param ids
     * @return
     */
    @RequestMapping("/startContracts")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public  ResponseData startContracts(@RequestParam("ids") Long[] ids){
        for (Long id :ids) {
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            try {
                StorageOut storageOut = storageOutService.getById(id);
                storageOut.setMark("");
                storageOut.setRepetition(uuid);
                StorageOutParam stor = new StorageOutParam();
                ToolUtil.copyProperties(storageOut,stor);
                storageOutService.update(stor);
            } catch (Exception e) {
                break;
            }
        }
        return ResponseData.success();
    }

    /**
     * 批量分配备货区
     */
    @RequestMapping("/pointsStockup")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData pointsStockup(String[] us,String[] ls
    		,StorageOutParam storageOutParam) {
    	for (int i = 0; i < us.length; i++) {
    		String getUnit = us[i];
    		String getLocation = ls[i];
    		//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
    		}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
    		}
    		StorageOutParam sop = new StorageOutParam();
    		sop.setGetUnit(getUnit);
    		sop.setGetLocation(getLocation);
    		sop.setDeliverId(userService.getDeliverId());
    		sop.setOutOrderStatus("webStorageOut");
        	Long deptId = userService.getDeptId();
    		List<StorageOutResult> listr = storageOutService.findListBySpec(sop,deptId);
			for (StorageOutResult sor : listr) {
				//更新拣货单 备货区
				StorageOutParam sop2 = new StorageOutParam();
				sor.setAreanumber(storageOutParam.getAreanumber());
				sor.setStockupareaId(storageOutParam.getStockupareaId());
				ToolUtil.copyProperties(sor,sop2);
				storageOutService.update(sop2);
				sop2 = new StorageOutParam();
				
				//更新货运订单 备货区
				OrderTransportParam otParam = new OrderTransportParam();
				otParam.setCustomerOrder(sor.getStorageOutNumber());
				OrderTransportResult otr = orderTransportService.findBySpec(otParam,null);
				if (otr!=null) {
					otr.setAreanumber(storageOutParam.getAreanumber());
					otr.setStockupareaId(storageOutParam.getStockupareaId());
					ToolUtil.copyProperties(otr,otParam);
					orderTransportService.update(otParam);
					otParam = new OrderTransportParam();
				}
			}
		}
        return ResponseData.success();
    }

    /**
     * 批量开始拣货
     */
    @RequestMapping("/startOutGoods")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResponseData startOutGoods(String[] us,String[] ls,String setMentiontime) {
    	ResponseData data = new ResponseData();
    	for (int i = 0; i < us.length; i++) {
    		String getUnit = us[i];
    		String getLocation = ls[i];
    		//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
    		}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
    		}
    		StorageOutParam sop = new StorageOutParam();
    		sop.setGetUnit(getUnit);
    		sop.setGetLocation(getLocation);
    		sop.setDeliverId(userService.getDeliverId());
    		sop.setOutOrderStatus("webStorageOut");
    		sop.setSetMentiontime(setMentiontime);
        	Long deptId = userService.getDeptId();
    		List<StorageOutResult> listr = storageOutService.findListBySpec(sop,deptId);
			for (StorageOutResult sor : listr) {
    			if (sor.getAreanumber()==null||sor.getAreanumber()=="") {
    				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
    				ResponseData rData = new ResponseData();
    				rData.setSuccess(false);
    				rData.setMessage("未分配备货区，无法开始");
    				return rData;
				}
			}
			data = storageOutDetailedService.recommend(listr);//生成
	        if (!data.getSuccess()) {
	            return data;
			}
	        if( listr.isEmpty()){
	        	data.setMessage("规划成功");
	        	data.setSuccess(true);
	            return data;
	        }
		}
        data.setMessage("规划成功");
        data.setSuccess(true);
        return data;
    }

    /**
     * 查询 收货单位列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(StorageOutParam storageOutParam,String condition) {
    	User user = userService.getcurrentUser();
    	Long deliverId = user.getDeliverId();
    	storageOutParam.setDeliverId(deliverId);
    	storageOutParam.setOutOrderStatus("webStorageOut");
    	Long deptId = user.getDeptId();
    	return this.storageOutService.findPageBySpec(storageOutParam,condition,deptId,user.getOperateId());
    }

    /**
     * 拣货单查询 
     */
    @ResponseBody
    @RequestMapping("/querylist")
    public LayuiPageInfo querylist(StorageOutParam storageOutParam,String condition,Long outCustomerId,String startSingleTime,String endSinglePutTime,String startTime,String endTime) {
    	User user = userService.getcurrentUser();
    	storageOutParam.setDeptId(user.getDeptId());
		//解决参数中的 英文括号
    	if(storageOutParam!=null){
        	String getUnit = storageOutParam.getGetUnit();
        	String getLocation = storageOutParam.getGetLocation();
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		storageOutParam.setGetUnit(getUnit);
    		}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		storageOutParam.setGetLocation(getLocation);
    		}
    	}
    	String singleOutTime = "";
    	if (ToolUtil.isNotEmpty(startSingleTime) && ToolUtil.isNotEmpty(endSinglePutTime)) {
    		singleOutTime = "'"+startSingleTime+"' and '"+endSinglePutTime+"'";
		}
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		storageOutParam.setSetMentiontime("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			startTime = DateUtil.getDate();
			endTime = DateUtil.getDate();
			storageOutParam.setSetMentiontime("'"+startTime+"' and '"+endTime+"'");
		}
        return this.storageOutService.querylistPageBySpec(storageOutParam,condition,null,outCustomerId,singleOutTime,user.getOperateId());
    }

    /**
     * 根据收货单位.地址   查询拣货单列表
     */
    @ResponseBody
    @RequestMapping("/storageOutlist")
    public LayuiPageInfo storageOutlist(StorageOutParam storageOutParam,String condition) {
    	Long deliverId = userService.getDeliverId();
		//解决参数中的 英文括号
    	if(storageOutParam!=null){
        	String getUnit = storageOutParam.getGetUnit();
        	String getLocation = storageOutParam.getGetLocation();
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		storageOutParam.setGetUnit(getUnit);
    		}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		storageOutParam.setGetLocation(getLocation);
    		}
    	}
    	storageOutParam.setDeliverId(deliverId);
    	storageOutParam.setOutOrderStatus("webStorageOut");
    	Long deptId = userService.getDeptId();
        return this.storageOutService.findPageByGet(storageOutParam,condition,deptId);
    }

    /**
     * 拣货单打印 查询收货单位
     */
    @ResponseBody
    @RequestMapping("/printlist")
    public LayuiPageInfo printlist(StorageOutParam storageOutParam,String condition) {
    	User user = userService.getcurrentUser();
    	if (condition!=null&&condition!="") {
    		condition = condition.replace("& #40;", "(");
    		condition = condition.replace("& #41;", ")");
		}
    	Long deptId = user.getDeptId();
        return this.storageOutService.findPageBySpec(storageOutParam,condition,deptId,user.getOperateId());
    }

    /**
     * 拣货单打印 
     * 查询拣货单信息
     */
    @ResponseBody
    @RequestMapping("/getPrintstorageOut")
    public StorageOutResult getPrintstorageOut(StorageOutParam storageOutParam) {
        return this.storageOutService.getPrintstorageOut(storageOutParam);
    }

    /**
     * 拣货单打印 
     * 修改拣货单打印次数
     */
    @ResponseBody
    @RequestMapping("/print")
    public ResponseData print() {
    	Long[] ids = CacheUtil.get("storageOutprintIds", "ids");
    	if (ids.length>0) {
			for (int i = 0; i < ids.length; i++) {
				StorageOutParam sop = new StorageOutParam();
				StorageOut sor = storageOutService.getById(ids[i]);
				if (sor.getPrintnum()!=null) {
					Integer printnum = Integer.parseInt(sor.getPrintnum());
					printnum = printnum+1;
					sor.setPrintnum(printnum.toString());
				} else {
					sor.setPrintnum("1");
				}
				ToolUtil.copyProperties(sor,sop);
				storageOutService.update(sop);
			}
			CacheUtil.remove("storageOutprintIds", "ids");//删除缓存
		}
        return ResponseData.success();
    }
    
    /**
     * 0出库
     */
    @ResponseBody
    @RequestMapping("/defect")
    public ResponseData defect(StorageOutDetailedParam param) {
    	ResponseData data = new ResponseData();
    	User user = userService.getcurrentUser();
    	StorageOutDetailed  storageOutDetailed = storageOutDetailedService.getById(param.getId());//拣货明细
    	
		StorageOutParam outParam2 = new StorageOutParam();
		outParam2.setStorageOutNumber(storageOutDetailed.getStorageOutNumber());
		StorageOutResult outResult2 = storageOutService.findBySpec(outParam2);//拣货单
		
		List<StorageOutDetailedResult> list = new ArrayList<StorageOutDetailedResult>();

        if (!"待拣货".equals(storageOutDetailed.getStorageOutStatus())) {
    		data.setMessage("已被其它人员操作");
    		data.setSuccess(false);
    		return data;
		}
		
        StorageOutDetailedParam StorageOutDetailedParamUpdate = new StorageOutDetailedParam();
        StorageOutDetailedParamUpdate.setId(param.getId());
        StorageOutDetailedParamUpdate.setNotes(param.getNotes());
        StorageOutDetailedParamUpdate.setStorageOutStatus("已拣货");
        StorageOutDetailedParamUpdate.setRealNum("0");
		StorageOutDetailedParamUpdate.setStorageOutUser(user.getUserId());//操作人user
		StorageOutDetailedParamUpdate.setStorageOutName(user.getName());//操作人
		this.storageOutDetailedService.update(StorageOutDetailedParamUpdate);
    	
    	StorageOutDetailedParam p = new StorageOutDetailedParam();
		p.setStorageOutNumber(storageOutDetailed.getStorageOutNumber());
		p.setStorageOutStatus("待拣货");
		if (ToolUtil.isNotEmpty(outResult2.getMark())) {
			 list = storageOutDetailedService.findListBymaekSpec(p,outResult2.getMark());
		} else {
			list = storageOutDetailedService.findListBySpec(p);
		}
		if (list.size()==0) {
			List<StorageOutResult> olist = new ArrayList<StorageOutResult>();
			if (ToolUtil.isNotEmpty(outResult2.getMark())) {
				StorageOutParam outParam = new StorageOutParam();
				outParam.setMark(outResult2.getMark());
				olist = storageOutService.findListByMakeSpec(outParam);
			} else {
				olist.add(outResult2);
			}
			
			for(StorageOutResult outResult : olist ) {
				StorageOutParam outParam = new StorageOutParam();
				outResult.setOutOrderStatus("PENDING_REVIEW");
	
				ToolUtil.copyProperties(outResult,outParam);
				storageOutService.update(outParam);
			}
		}
		return ResponseData.success();
    }

}


